package com.ks.core.framework.cpsupload.demos.resp;

import java.util.Map;
import java.util.function.Supplier;

// ========== 响应统一门面（核心入口） ==========
public class UnifiedResponseFacade {
    // 工厂映射
    private static final Map<String, Supplier<ResponseAdapterFactory>> factorySuppliers = Map.of(
        "WECHAT", WechatResponseAdapterFactory::new
//        "ALIPAY", AlipayResponseAdapterFactory::new,
//        "UNIONPAY", UnionpayResponseAdapterFactory::new
    );
    
    public UnifiedResponse buildResponse( String channel,  String operationType,  Map<String, Object> rawData ) {
        // 1. 获取适配器工厂
        ResponseAdapterFactory factory = createFactory(channel);
        
        // 2. 创建响应组件
        ResponseComponent component = createComponent(factory, operationType, rawData);
        
        // 3. 构建统一响应
        return buildFromComponent(component);
    }
    
    private ResponseAdapterFactory createFactory(String channel) {
        Supplier<ResponseAdapterFactory> supplier = factorySuppliers.get(channel);
        if (supplier == null) {
            throw new IllegalArgumentException("不支持的支付渠道: " + channel);
        }
        return supplier.get();
    }
    
    private ResponseComponent createComponent( ResponseAdapterFactory factory,  String operationType, Map<String, Object> rawData ) {
        switch (operationType.toUpperCase()) {
            case "PAYMENT":
                return factory.createPaymentResponse(rawData);
            case "REFUND":
                return factory.createRefundResponse(rawData);
            case "QUERY":
                return factory.createQueryResponse(rawData);
            case "CALLBACK":
                return factory.createCallbackResponse(rawData);
            default:
                throw new IllegalArgumentException("不支持的操作类型: " + operationType);
        }
    }
    
    private UnifiedResponse buildFromComponent(ResponseComponent component) {
        return new UnifiedResponse.Builder()
            .success("SUCCESS".equals(component.getCode()))
            .code(component.getCode())
            .message(component.getMessage())
            .operationType(component.getOperationType())
            .businessData(component.getStandardData())
            .build();
    }
}